package com.begamer.card.log;

import java.io.File;
import java.util.Calendar;
import java.util.Date;

import org.apache.log4j.FileAppender;
import org.apache.log4j.spi.LoggingEvent;

import com.begamer.card.common.util.StringUtil;

public class DateFileAppender extends FileAppender
{
	private String path;
	private String filename;
	
	
	private File m_path;
	private Calendar m_calendar;
	private long m_tomorrow = 0L;
	
	public DateFileAppender()
	{
		
	}
	
	public DateFileAppender(String path, String filename)
	{
		this.path = path;
        this.filename = filename;
        activateOptions();
    }
	
	 //=======================Public Methods=====================//
    public void activateOptions() 
    {
        if (filename == null)
        {
        	filename = "";
        }
        if ((path == null) || (path.length() == 0))
        {
        	path = ".";
        }
        //创建文件夹
        m_path = new File(path);
        if (!m_path.isAbsolute()) 
        {
            String base = System.getProperty("catalina.base");
            if (base != null) {
            	m_path = new File(base, path);
            }
        }
        m_path.mkdirs();
        if (m_path.canWrite()) {
            m_calendar = Calendar.getInstance(); // initialized
        }
    }

    public void append(LoggingEvent event) {
        if (this.layout == null) {
            errorHandler.error("No layout set for the appender named [" + name +"].");
            return;
        }
        if (this.m_calendar == null) {
            errorHandler.error("Improper initialization for the appender named [" + name +"].");
            return;
        }
        long n = System.currentTimeMillis();
        if (n >= m_tomorrow) {
            m_calendar.setTime(new Date(n));
            String datestamp = StringUtil.getDate(n); 
            tomorrow(m_calendar); 
            m_tomorrow = m_calendar.getTime().getTime();
            File newFile = new File(m_path, datestamp +"-"+ filename);
            this.fileName = newFile.getAbsolutePath();
            super.activateOptions(); 
        }
        if (this.qw == null) { // should never happen
            errorHandler.error(
                    "No output stream or file set for the appender named [" +
                    name + "].");
            return;
        }
        subAppend(event);

    }
    
    public static void tomorrow(Calendar calendar) {
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH) + 1;
        calendar.clear(); // clear all fields
        calendar.set(year, month, day); // set tomorrow's date
    }
    
	public String getPath()
	{
		return path;
	}

	public void setPath(String path)
	{
		this.path = path;
	}

	public String getFilename()
	{
		return filename;
	}

	public void setFilename(String filename)
	{
		this.filename = filename;
	}
    
}
